package cn.com.klun.tjy.test.ZookeeperTest;


import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Random;

import static org.apache.zookeeper.ZooDefs.Ids.OPEN_ACL_UNSAFE;

public class ZkMaster implements Watcher {

    private static Logger logger = LoggerFactory.getLogger(ZkMaster.class);
    static ZooKeeper zk;
    String hostPort;
    static String serverId = Integer.toHexString(new Random().nextInt());
    static boolean isLeader = false;

    // 检查是否创建主节点
    static boolean checkMaster() {
        while(true){
            try {
                Stat stat = new Stat();
                byte data[] = zk.getData("/master",false,stat);
                isLeader = new String(data).equals(serverId);
                return true;
            } catch (Exception e) {
                return false;
            }
        }
    }
    // 同步运行机制
    void runForMaster() throws  InterruptedException {
        while(true) {
            try {
                zk.create("/master",
                        serverId.getBytes(),
                        OPEN_ACL_UNSAFE,
                        CreateMode.EPHEMERAL);
                isLeader = true;
                break;
            } catch (KeeperException.NodeExistsException e) {
                isLeader = false;
                break;
            } catch (KeeperException.ConnectionLossException e) {
            } catch (KeeperException e) {
                e.printStackTrace();
            }
        }
    }

    private ZkMaster(String hostPort) {
        this.hostPort = hostPort; //1
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        logger.debug("一个事务监听器{}", watchedEvent);//3
    }
    void startZK() throws IOException {
        zk = new ZooKeeper(hostPort,15000,this);//2
    }
    void stopZK() throws InterruptedException {
        zk.close();
    }
    public static void main(String args[]) throws Exception {

        ZkMaster zk = new ZkMaster("192.168.137.12:2181");
        zk.startZK();
        zk.runForMaster();
        Thread.sleep(500);
        if(isLeader){
            System.out.println("************是leader");
            Thread.sleep(5000);
        } else {
            System.out.println("************或许别人是leader");
        }
        zk.stopZK();
    }

}
